<%@page import="com.core.sysDict.SysDictJsp"%>
<%@ page import="com.interfaces.GuaranteeController" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<!--
This is a starter template page. Use this page to start your new project from
scratch. This page gets rid of all links and provides the needed markup only.
-->
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>招保信息管理</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <%
        String path = request.getContextPath();
        path = "/".equals(path)?"":path;
        request.setAttribute("path", path);
        String sysDictJson=SysDictJsp.getSysDictJson(session);
    %>
    <script type="text/javascript">
        var path = "${path}";
    </script>

    <!-- Bootstrap 3.3.6 -->
    <link rel="stylesheet" href="${path}/public/adminlte/bootstrap/css/bootstrap.min.css">

    <!-- modal -->
    <link rel="stylesheet" href="${path}/js/bootstrap-modal/css/bootstrap-modal-bs3patch.css">
    <link rel="stylesheet" href="${path}/js/bootstrap-modal/css/bootstrap-modal.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="${path}/public/font-awesome-4.7.0/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="${path}/public/ionicons/ionicons.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="${path}/public/adminlte/plugins/datatables/dataTables.bootstrap.css">
    <!-- bootstrap datepicker -->
    <link rel="stylesheet" href="${path}/public/adminlte/plugins/datepicker/datepicker3.css">
    <!-- Select2 -->
    <link rel="stylesheet" href="${path}/public/adminlte/plugins/select2/select2.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="${path}/public/adminlte/dist/css/AdminLTE.min.css">

    <!-- AdminLTE Skins. We have chosen the skin-blue for this starter
          page. However, you can choose any other skin. Make sure you
          apply the skin class to the body tag so the changes take effect.
    -->
    <link rel="stylesheet" href="${path}/public/adminlte/dist/css/skins/_all-skins.min.css">

    <link rel="stylesheet" href="${path}/css/common.css">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<!--
BODY TAG OPTIONS:
=================
Apply one or more of the following classes to get the
desired effect
|---------------------------------------------------------|
| SKINS         | skin-blue                               |
|               | skin-black                              |
|               | skin-purple                             |
|               | skin-yellow                             |
|               | skin-red                                |
|               | skin-green                              |
|---------------------------------------------------------|
|LAYOUT OPTIONS | fixed                                   |
|               | layout-boxed                            |
|               | layout-top-nav                          |
|               | sidebar-collapse                        |
|               | sidebar-mini                            |
|---------------------------------------------------------|
-->
<body >
<!-- Modal导入归国 -->
<div class="modal fade" id="myInputExcel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

    <div class="modal-dialog" role="document" style="width: 400px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">导入归国报告书XLS</h4>
            </div>
            <div class="modal-body">
                <form style="height:300px; overflow:auto;"enctype="multipart/form-data" id="uploadForm">
                    <div class="form-group">
                        <label for="recipient-name" class="control-label">上传文件:</label>
                        <input type="file"  class="form-control" id="fileUpload" name="file1">
                        <br/><span style="color: red" id="fileTypeError"></span>　
                    </div>
                    <div class="form-group" hidden="hidden">
                        <label for="recipient-name" class="control-label">招保id:</label>
                        <input type="text" name="txtId" class="form-control" id="txtId">
                    </div>
                    <div class="form-group" hidden="hidden">
                        <label for="recipient-name" class="control-label">其余人数:</label>
                        <input type="text" name="otherNum" class="form-control" id="otherNum">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="upload">上 传</button>
            </div>
        </div>
    </div>
</div>
<div class="container">

    <div class="box box-primary">
        <!-- /.box-header -->
        <div class="box-body">
            <div class="row">
                <div class="col-md-12">
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-3">
                                <label for="firstPersonName">1号人姓名</label>
                            </div>
                            <div class="col-md-3">
                                <label for="firstPersonName">状态:</label>
                            </div>
                            <div class="col-md-4">
                                <label for="firstPersonName">添加日期:</label>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <input type="text" class="form-control" id="firstPersonName">
                            </div>
                            <div class="col-md-3">
                                <select  class="form-control" id="searchState">
                                </select>
                            </div>
                            <div class="col-md-4">
                                <div class="input-group input-daterange  pull-right">
                                    <input type="text" id="startDate" class="form-control">
                                    <div class="input-group-addon">to</div>
                                    <input type="text" id="endDate" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" id="btnSearch" class="btn btn-primary">搜 索</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-12 text-right">
                    <button type="submit"  onclick="btnBatUpdate(1)" class="btn btn-primary">批量提交</button>
                    <button type="submit" id="btnAdd" class="btn btn-primary">新增招保</button>
                </div>
            </div>
        </div>
    </div>
    <!-- /.box -->
    <div class="box box-primary">
        <!-- /.box-header -->
        <div class="box-body">
            <table id="dg" class="table table-bordered table-hover">
            </table>
        </div>
        <!-- /.box-body -->
    </div>
</div>

<!-- ./wrapper -->

<div class="modal fade" id="modelContainer" role="basic" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
        </div>
    </div>
</div>

<!-- REQUIRED JS SCRIPTS -->

<!-- jQuery 2.2.3 -->
<script src="${path}/public/adminlte/plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="${path}/public/adminlte/bootstrap/js/bootstrap.min.js"></script>
<!-- modal -->
<script src="${path}/js/bootstrap-modal/js/bootstrap-modal.js"></script>
<script src="${path}/js/bootstrap-modal/js/bootstrap-modalmanager.js"></script>
<!-- DataTables -->
<script src="${path}/public/adminlte/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="${path}/public/adminlte/plugins/datatables/dataTables.bootstrap.min.js"></script>
<!-- Select2 -->
<script src="${path}/public/adminlte/plugins/select2/select2.full.min.js"></script>
<!-- SlimScroll -->
<script src="${path}/public/adminlte/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="${path}/public/adminlte/plugins/fastclick/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="${path}/public/adminlte/dist/js/app.min.js"></script>
<!-- 字典-->
<script src="${path}/js/sysDict.js"></script>
<script src="${path}/js/input.js"></script>
<!-- bootstrap datepicker -->
<script src="${path}/public/adminlte/plugins/datepicker/bootstrap-datepicker.js"></script>
<script>
    var table;
    var url = window.location.search;
    var arr=url.split('&');
    var curid = "tab_"+arr[arr.length-2];
    console.info(curid);
    var sysDict='<%=sysDictJson%>';
    var re = JSON.parse(sysDict);
    (function($){
        $.fn.datepicker.dates['zh-CN'] = {
            days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
            daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
            daysMin:  ["日", "一", "二", "三", "四", "五", "六"],
            months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
            today: "今日",
            clear: "清除",
            format: "yyyy年mm月dd日",
            titleFormat: "yyyy年mm月",
            weekStart: 1
        };
    }(jQuery));
    $('.input-daterange input').each(function() {
        autoclose: true,
            $(this).datepicker({
                language:'zh-CN',
                format: 'yyyy-mm-dd',
            });
    });
    window.onload=function(){
        init();
        $("#checkAll").click(function () {
            var check = $(this).prop("checked");
            $(".checkchild").prop("checked", check);
        });
    };
    function formatRepo (repo) {
        if (repo.loading) {return repo.text;}
        return repo.text+"("+repo.id+")";
    }
    function formatRepoSelection (repo) {
        return repo.text ;
    }
    getSelect($("#searchState"),'1001',null,re,0);
    function init() {

        table=$('#dg').DataTable({
            "iDisplayLength" : 10,
            "paging": true,
            "lengthChange": true,
            "bSort" : false,
            "pagingType": "input",
            "processing" : true,
            "serverSide" : true,
            "searching": false,
            "ordering": false,
            "autoWidth": false,
            "ajax":{
                "url":"${path}<%=GuaranteeController.URL_DB_SEARCH%>?&"+arr[arr.length-1],
                "type":"post",
            },
            "columns":[
                {
                    "data":"id",
                    "title":"<input type='checkbox' class='check' id='checkAll'>",
                    "defaultContent":"",
                    "render":function(data, type, row, meta){
                        return '<input type="checkbox" name="subcheck" class="checkchild"  value="' + meta.row + '" />';
                    },
                    "bSortable": false
                },
                { "data": "id",
                    "title":"修改",
                    "render":function(data, type, full, meta){
                        return'<A href="javascript:updateFund(&quot;'+data+'&quot;);"><img src="${path}/img/document-edit.png"/></A>';
                    },
                },
                { "data": "destVisaId","title":"受付番号","defaultContent":"" },
                { "data": "firstPersonName","title":"1号人姓名","defaultContent":"" },
                { "data": "number","title":"其余人数","defaultContent":""},
                { "data": "visaType", "title":"签证类型","defaultContent":"", "render": function(data, type, full) { return getKey_caption('1002',data,re);}},
                { "data": "incomingDate", "title":"入境日期","defaultContent":""},
                { "data": "leaveDate", "title":"出境日期","defaultContent":""},
                { "data": "state", "title":"状态","defaultContent":"","render": function(data, type, full) { return getKey_caption('1001',data,re);}},
                { "data": "id", "title":"导入/状态","defaultContent":"","render": function(data, type, row,meta) { var tt=row.returnReportState;var showTXT=getKey_caption('1006',tt,re);  return'<button href="#" data-toggle="modal" onclick="inputExcel(\'' + meta.row + '\')">导入归国报告</button>'+'<div >(' + showTXT + ')</div>';}},
                { "data": "id", "title":"下载归报/状态","defaultContent":"","render": function(data, type, row,meta) { var tt=row.returnReportPdfDownloadState; var showTXT=getKey_caption('1007',tt,re);  return'<button href="#" onclick="outputPDF(\'' + meta.row + '\')">下载归国PDF</button>'+'<div >(' + showTXT + ')</div>';}},
                { "data": "returnReportState", "title":"归报状态","defaultContent":"","visible": false, "render": function(data, type, full) { return getKey_caption('1006',data,re);}},
                { "data": "returnReportPdfDownloadState", "title":"Pdf状态","defaultContent":"","visible": false,  "render": function(data, type, full) { return getKey_caption('1007',data,re);}},
            ],
            "language": {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": " ",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "表中数据为空",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                }
            }
        });
    }
    $("#btnAdd").click(function () {
        var CustodianID=new Date().getTime()+''+Math.floor(Math.random() * 8998 + 1000);
        parent.addTab({title: "新增招保信息", url:"${path}<%=GuaranteeController.URL_GOTO_ADD_UPDATE_PAGE%>?&"+CustodianID+"&"+curid, id: CustodianID, close: true, single:true,act:1});
    });
    $("#upload").click(function () {
        $("#fileTypeError").html('');
        var fileName = $('#fileUpload').val();
        console.info(fileName);
        console.info(typeof(fileName));
        var fileTypetemp = fileName.split(".");
        var fileType =fileTypetemp[fileTypetemp.length-1].toLowerCase();
        console.info(fileType);
        if(fileType=='xls'){
            $.ajax({
                url:"${path}<%=GuaranteeController.URL_UPLOAD%>",
                type: 'POST',
                cache: false,
                data: new FormData($('#uploadForm')[0]),
                processData: false,
                contentType: false,
                success:function(data){
                    console.info(data);
                    if(data==101){
                        $("#fileTypeError").html('*文件上传出错,检测上传文件是否正确!');
                    }
                    if(data==102){
                        $("#fileTypeError").html('*文件上传时读取出错,检测上传文件是否正确!');
                    }
                    if(data==103){
                        $("#fileTypeError").html('*文件上传时出错,一号人姓名不匹配!请选择相对应的文件!');
                    }
                    if(data==104){
                        $("#fileTypeError").html('*1号人不存在!!');
                    }
                    if(data==105){
                        $("#fileTypeError").html('*文件未找到');
                    }
                    if(data==106){
                        $("#fileTypeError").html('*导入归报的人数和其余人数不匹配,请检查后重新导入');
                    }
                    if(data==107){
                        $("#fileTypeError").html('*导入归报的居住地域超过限定长度!(默认不能超过6个字符!)');
                    }
                    if(data==200){
                        alert("导入成功!")
                        $('#myInputExcel').modal('hide')
                        table.ajax.reload();
                    }
                    if(data=='fileTypeError'){
                        $("#fileTypeError").html('*上传文件类型错误,支持类型: .xsl');
                    }
                    $("input[name='enclosureCode']").attr('value',data);
                }
            });
        }else{
            $("#fileTypeError").html('*上传文件类型错误,支持类型: .xls');
        }
    });
    $("#btnSearch").click(function(){
        var searchState =$('#searchState').val();
        if(searchState=="#"){
            searchState="";
        }
        var param = {
            "firstPersonName": $('#firstPersonName').val(),
            "state":searchState,
            "beginDate":$('#startDate').val(),
            "finnishDate":$('#endDate').val()
        };
        console.info(param);
        table.settings()[0].ajax.data = param;
        table.ajax.reload();
    });

    function updateFund(code){
        var CustodianID=new Date().getTime()+''+Math.floor(Math.random() * 8998 + 1000);
        parent.addTab({title: "修改招保信息", url:"${path}<%=GuaranteeController.URL_GOTO_UPDATE_PAGE%>?id="+code+"&"+CustodianID+"&"+curid, id: CustodianID, close: true, single:true});
    }
    function inputExcel(code){
        var rowTarget=table.row(code).data();
        if(rowTarget.state!=3){
            alert("当前招保状态不允许这样操作,只有推送成功才能导入!")
            $('#myInputExcel').modal('hide')
            return;
        }
        $('#myInputExcel').modal('show');
        console.info(code);
        $('#myInputExcel').on('shown.bs.modal', function (e) {
            console.info(rowTarget.id)
            $('#txtId').val(rowTarget.id);
            $('#otherNum').val(rowTarget.number);
        });
    };
    //	   导出pdf
    function outputPDF(code){
        var rowTarget=table.row(code).data();
        $.ajax({
            type:"POST",
            url:"${path}<%=GuaranteeController.URL_CHECKDPDF%>",
            data:{id:rowTarget.id},
            success:function(result){
                if(result==108){
                    alert("PDF未导入到系统中!");
                }else if(result==105){
                    alert("文件下载出错!");
                }else if(result==200){
                    window.location.href="${path}<%=GuaranteeController.URL_DOWNLOADPDF%>?"+"id="+rowTarget.id
                }
            },

        });

    };
    function btnBatUpdate(code){
        var show="";
        var checkedNum = $("input[name='subcheck']:checked").length;
        if(checkedNum==0){
            alert("请至少选择一项!");
            return false;
        }
        if(code==1){
            show="确定提交所选项目?"
        }
        if(confirm(show)){
            var checkedList = new Array();
            var flag=0;
            $("input[name='subcheck']:checked").each(function(){
                var index=$(this).val();
                console.info(index)
                var rowTarget=table.row(index).data();
                console.info(rowTarget)
                console.info("快进来了")
                if(rowTarget.state==1|| rowTarget.state==3){
                    alert("招保id为:"+rowTarget.id+"的状态不允许执行该操作,请检查后重试!");
                    flag=1;
                }

                checkedList.push(rowTarget.id);
                console.info(checkedList+"checkList");
            });
            if(flag==1){
                return false;
            }
            $.ajax({
                type:"POST",
                url:"${path}<%=GuaranteeController.URL_UPDATESTATE%>",
                data:{"delitems":checkedList.toString(),"afterState":code},
                success:function(result){
                    var re = JSON.parse(result);
                    if(re.returnCode=="0"){
                        alert("批量提交成功!")
                        $("[name='checkbox2']:checkbox").attr("checked",false);
                        location.reload();
                    }else{
                        alert(re.msg);
                    }
                },
                error:function(request) {      // 设置表单提交出错
                    alert(request);  //登录错误提示信息
                }
            });
        }
    }
    function freshOK(){
        console.info("success");
        table.draw( false );
//        location.reload();
    };

</script>
</body>
</html>